package com.jpcc.vw.onlineRadio.base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.CustomIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.cns.android.atmospherelamp.AtmosphereLampManager;
import com.j256.ormlite.stmt.query.In;
import com.jpcc.vw.onlineRadio.R;
import com.jpcc.vw.onlineRadio.activity.MainActivity;
import com.jpcc.vw.onlineRadio.application.MusicApplication;
import com.jpcc.vw.onlineRadio.constants.Constants;
import com.jpcc.vw.onlineRadio.model.IRadio;
import com.jpcc.vw.onlineRadio.model.action.RequestFocusRefreshAction;
import com.jpcc.vw.onlineRadio.model.bean.BaseBean;
import com.jpcc.vw.onlineRadio.model.bean.VIPInfoBean;
import com.jpcc.vw.onlineRadio.model.impl.RadioImpl;
import com.jpcc.vw.onlineRadio.service.AlbumRadioAudioPlayer;
import com.jpcc.vw.onlineRadio.service.AudioFocusManager;
import com.jpcc.vw.onlineRadio.utils.CommonSubscriber;
import com.jpcc.vw.onlineRadio.utils.PermissionReq;
import com.jpcc.vw.onlineRadio.utils.PreferenceUtils;
import com.jpcc.vw.onlineRadio.utils.ProcessInfoUtils;
import com.jpcc.vw.onlineRadio.utils.ToastUtils;
import com.orhanobut.logger.Logger;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;


/**
 * Activity基础类库
 * Created by liukanshan on 2016/12/8.
 */

public abstract class BaseActivity extends AppCompatActivity {

    private MaterialDialog progressDialog;
    public View emptyView;
//    protected PlayAlbumRadioService playService;
//    private ServiceConnection serviceConnection;

    @BindView(R.id.imv_top_bottom_line)
    @Nullable
    ImageView imv_top_bottom_line;
    @BindView(R.id.imv_back_main)
    @Nullable
    ImageView imv_back_main;

    private MosphereReceiver mosphereReceiver;
    private AudioFocusManager audioFocusManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setStatusBar();
        initWindow();
        setContentView(getLayoutId());
        audioFocusManager = new AudioFocusManager(this);
        setStatusBar();
        ButterKnife.bind(this);
        MusicApplication.GetInstance().addActivity(this);

        mosphereReceiver = new MosphereReceiver();
        IntentFilter mosphereFilter = new IntentFilter(CustomIntent.ACTION_ATMOSPHERE_LAMP_STATE);
        this.registerReceiver(mosphereReceiver, mosphereFilter);


        if (Constants.isRelease) {
            if (imv_top_bottom_line != null) {
                try {
//                    Logger.i("atmosphere color--->" + AtmosphereLampManager.getInstance(BaseActivity.this).getAtmosphereLampColor());
                    Logger.i("atmosphere color--->" + AtmosphereLampManager.getInstance(BaseActivity.this).getHmiAtmosphereLampColor());
                    boolean atmosphereOn = false;
//                    atmosphereOn = AtmosphereLampManager.getInstance(BaseActivity.this).isAtmosphereLampOn();
                    atmosphereOn = AtmosphereLampManager.getInstance(BaseActivity.this).isHmiAtmosphereLampOn();
                    Logger.i("atmosphere on/off--->" + atmosphereOn);
                    if (atmosphereOn) {
//                        String color = AtmosphereLampManager.getInstance(BaseActivity.this).getAtmosphereLampColor();
                        String color = AtmosphereLampManager.getInstance(BaseActivity.this).getHmiAtmosphereLampColor();
                        if (!TextUtils.isEmpty(color)) {
                            imv_top_bottom_line.setColorFilter(Color.TRANSPARENT);
                        } else {
                            imv_top_bottom_line.setColorFilter(Color.parseColor(color));
                        }
                    } else {
                        imv_top_bottom_line.setColorFilter(Color.TRANSPARENT);
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }

        if(imv_back_main!=null){
            imv_back_main.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent=new Intent(BaseActivity.this,MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                }
            });
        }
        initProgressDialog();
        emptyView = View.inflate(this, R.layout.activity_empty_list_view, null);
        setupView();
        setupData();



    }

    public  void initWindow() {
    }


    @Override
    protected void onResume() {
        super.onResume();



//以下是之前的焦点策略实现
//        if(Constants.FLAG_TEMP_AUDIO_FGOCUS){
//            Logger.i("base activity is playing-->"+AlbumRadioAudioPlayer.get().isPlaying());
//            Logger.i("base activity is FLAG_PAUSE_MANUAL-->"+Constants.FLAG_PAUSE_MANUAL);
//            if (Constants.isRelease&&ProcessInfoUtils.isForeground(BaseActivity.this)) {
//                if ((!AlbumRadioAudioPlayer.get().isPlaying()) && (!Constants.FLAG_PAUSE_MANUAL)) {
//                    AlbumRadioAudioPlayer.get().startPlayer();
//                    Logger.i("base onresume-->playing");
//                }
//                else if(!Constants.FLAG_FOCUS_ON_SELF){
//                    AudioFocusManager audioFocusManager=AlbumRadioAudioPlayer.get().getAudioFocusManager();
//                    if(audioFocusManager!=null){
//                        audioFocusManager.requestAudioFocus();
//                        Logger.i("base onresume-->request audioFocus");
//                        Logger.i("base onresume-->send eventbus");
//                        RequestFocusRefreshAction action=new RequestFocusRefreshAction();
//                        EventBus.getDefault().post(action);
//
//
//                    }
//                }
//            }
//        }
    }


    private void queryVipInfo(){
        IRadio radioModel=new RadioImpl();
        radioModel.QueryVIPInfo().subscribe(new CommonSubscriber<VIPInfoBean>() {
            @Override
            public void onSuccess(VIPInfoBean response) {
                if (response.getData() != null && response.getData().isVipFlag()) {
                    PreferenceUtils.SaveVIPStatus(true);
                } else {
                    PreferenceUtils.SaveVIPStatus(false);
                }
            }

            @Override
            public void onFailure(BaseBean response) {
            }
        });
    }

    public void initProgressDialog() {
        progressDialog = new MaterialDialog.Builder(this)
                .progress(true, 0)
                .content(getResources().getString(R.string.string_102))
                .autoDismiss(false)
                .cancelable(true)
                .build();
    }

    public void setStatusBar() {
        this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); //隐藏状态栏
    }

//    public void setStatusBarVisibility(boolean show){
//        if (show) {
//            this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
//        } else {
//            this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); //隐藏状态栏
//        }
//    }

    public void showProgress() {
        progressDialog.show();
    }

    public void hideProgress() {
        progressDialog.dismiss();
    }

    public abstract int getLayoutId();

    public abstract void setupView();

    public void setupData() {
//        Intent intent = new Intent(this, PlayAlbumRadioService.class);
//        serviceConnection = new PlayServiceConnection();
//        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    public <T extends View> T $(int id) {
        return (T) super.findViewById(id);
    }

    protected void hidenInput(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

//    private void bindService() {
//        Intent intent = new Intent(this, PlayAlbumRadioService.class);
//        serviceConnection = new PlayServiceConnection();
//        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
//    }

//    private class PlayServiceConnection implements ServiceConnection {
//        @Override
//        public void onServiceConnected(ComponentName name, IBinder service) {
//            playService = ((PlayAlbumRadioService.PlayBinder) service).getService();
//            onServiceBound();
//        }
//
//        @Override
//        public void onServiceDisconnected(ComponentName name) {
//            Log.e(getClass().getSimpleName(), "service disconnected");
//        }
//    }


    protected void onServiceBound() {
    }

//    private void setSystemBarTransparent() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            // LOLLIPOP解决方案
//            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//            getWindow().setStatusBarColor(Color.TRANSPARENT);
//        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            // KITKAT解决方案
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//        }
//    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionReq.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
//        super.onSaveInstanceState(outState, outPersistentState);
    }


    class MosphereReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean rgbOn = intent.getBooleanExtra(CustomIntent.EXTRA_HMI_LAMP_ON, false);
            String rgbColor = intent.getStringExtra(CustomIntent.EXTRA_HMI_LAMP_COLOR);
            Logger.i("atmosphereRgbOn-->" + rgbOn);
            Logger.i("atmosphereRgbColor-->" + rgbColor);
            if (!TextUtils.isEmpty(rgbColor)) {
//                if (rgbOn) {
//                    layout_detail.setBackgroundColor(Color.parseColor(rgbColor));
//                } else {
//                    layout_detail.setBackgroundColor(Color.parseColor("#10c4aa00"));
//                }
                doAtmosphere(rgbOn, rgbColor);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(mosphereReceiver);
    }

    public void doAtmosphere(boolean rgbOn, String color) {
        if (rgbOn) {
            if (imv_top_bottom_line != null) {
                if (!TextUtils.isEmpty(color)) {
                    imv_top_bottom_line.setColorFilter(Color.parseColor(color));
                } else {
                    imv_top_bottom_line.setColorFilter(Color.TRANSPARENT);
                }
            }
        } else {
            if (imv_top_bottom_line != null) {
                imv_top_bottom_line.setColorFilter(Color.TRANSPARENT);
            }
        }
    }

    //    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        if (serviceConnection != null) {
//            unbindService(serviceConnection);
//        }
//    }
}
